package com.qf.web.controller;

import com.qf.domain.Cart;
import com.qf.domain.Goods;
import com.qf.domain.User;
import com.qf.service.CartService;
import com.qf.service.GoodsService;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * projectName:myxiaomi
 * author:LiPengChong
 * time:2024/4/17 15:16
 * description:
 */
@WebServlet("/cartservlet")
public class CartServlet extends BaseServlet {
    //【添加购物车】
    //http://localhost:8080/cartservlet?method=addCart&goodsId=1&number=1
    public String addCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2.获取参数
        String goodsId = request.getParameter("goodsId");
        String number = request.getParameter("number");
        //3.校验
        if (StringUtils.isEmpty(goodsId)) {
            request.setAttribute("msg", "商品id不能为空");
            return "/message.jsp";
        }
        int num = 1;
        if (!StringUtils.isEmpty(number)) {
            try {
                num = Integer.parseInt(number);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        try {
            //4.调用业务逻辑
            CartService cartService = new CartServiceImpl();
            int good_id = Integer.parseInt(goodsId);
            //调用GoodsService,查询商品信息
            GoodsService goodsService = new GoodsServiceImpl();
            Goods goods = goodsService.findById(good_id);//通过得到的商品id，得到商品信息，再通过get方法得到商品单价(price)

            //查看购物车是否存在这个商品
            Cart cart = cartService.find(user.getId(), good_id);//通过用户id和商品id查询购物车
            if (cart != null) {//如果存在，只做个更新操作
                cart.setNum(cart.getNum() + num);//原有的数量加上新增的一起通过setNum方法赋值给num，做更新操作
                cart.setMoney(goods.getPrice().multiply(new BigDecimal(cart.getNum())));//将价格也做更新处理
                cartService.modify(cart);
            } else {//不存在，做添加操作
                cart = new Cart(user.getId(), good_id, num, goods.getPrice().multiply(new BigDecimal(num)));
                cartService.add(cart);
            }

            //转发重定向
            return "redirect:/cartSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "添加购物车失败" + e.getMessage());
            return "/message.jsp";
        }
    }

    //【查看购物车】
    //http://localhost:8080/cartservlet?method=getCart
    public String getCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        try {
            //调用业务逻辑
            CartService cartService = new CartServiceImpl();
            List<Cart> cartList = cartService.find(user.getId());
            //转发重定向
            request.setAttribute("cartList", cartList);
            return "/cart.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "查询购物车失败" + e.getMessage());
            return "/message.jsp";
        }
    }

    //【AJAX操作购物车】
    //cartservlet?method=addCartAjax&goodsId="+pid+"&number=1
    public String addCartAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        String goodsId = request.getParameter("goodsId");
        String number = request.getParameter("number");
        //3.非空校验
        if (StringUtils.isEmpty(goodsId)) {
            request.setAttribute("msg", "商品id不能为空");
            return "/message.jsp";
        }
        try {
            //4.调用业务逻辑
            int goods_id = Integer.parseInt(goodsId);
            int num = Integer.parseInt(number);
            CartService cartService = new CartServiceImpl();
            if (num == 0) {//num=0执行删除操作(删除商品)
                cartService.remove(user.getId(), goods_id);//通过用户id和商品id找到对应的商品进行删除
            } else if (num == 1 || num == -1) {//更新功能
                //当num=1时，添加商品，等于-1时，减少商品
                //查找商品
                Cart cart = cartService.find(user.getId(), goods_id);
                if (cart != null) {//如果不为空，修改购物车中对应的商品数量和价格
                    GoodsService goodsService = new GoodsServiceImpl();
                    Goods goods = goodsService.findById(goods_id);//通过id找到商品
                    cart.setNum(cart.getNum() + num);//计算现在的商品数量
                    cart.setMoney(goods.getPrice().multiply(new BigDecimal(cart.getNum())));
                    cartService.modify(cart);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg", "更新购物车失败"+e.getMessage());
            return "/message.jsp";
        }
        return null;//null代表JSNO，AJAX处理
    }

    //【清空购物车】
    //cartservlet?method=clearCartAjax
    public String clearCartAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        try {
            //2.调用业务逻辑
            CartService cartService = new CartServiceImpl();
            cartService.clear(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "清空购物车失败"+e.getMessage());
            return "/message.jsp";
        }
        return null;
    }
}